#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

import json

from common.const import SysData
from db2.comm.constant import ParamField, DB2Type
from db2.comm.util.common_util import Db2CommonUtil
from db2.comm.const import Db2JsonConstant


class Param:

    def __init__(self, param_dict, pid=None):
        if pid is not None:
            self.pid = pid
        self.param_dict = param_dict
        self._username = None
        self._password = None

    @property
    def app_env(self):
        app_env = self._get_param_field(ParamField.APP_ENV)
        return app_env if app_env else {}

    @property
    def application(self):
        application = self._get_param_field(ParamField.APPLICATION)
        if application is None:
            # 特殊处理v2的applications
            application = self._get_param_field(ParamField.APPLICATIONS)
            if not application:
                return {}
            application = application[0]
        return application if application else {}

    @property
    def env_extend_info(self):
        extend_info = self._get_param_field(ParamField.EXTEND_INFO, self.app_env)
        return extend_info if extend_info else {}

    @property
    def app_extend_info(self):
        app_extend_info = self._get_param_field(ParamField.EXTEND_INFO, self.application)
        return app_extend_info if app_extend_info else {}

    @property
    def env_auth(self):
        auth = self._get_param_field(ParamField.AUTH, self.app_env)
        return auth if auth else {}

    @property
    def app_auth_key(self):
        """处理接口的application，获取用户名"""
        if not self._username:
            self._get_all_envinfo()
        return self._username

    @property
    def app_auth_pwd(self):
        """处理接口的application，获取用户名"""
        if not self._password:
            self._get_all_envinfo()
        password = self._password
        self._password = None
        return password

    @property
    def app_auths_key(self):
        """特殊处理v2接口的applications，获取用户名"""
        auth_key = Db2CommonUtil.safe_get_environ(f'{Db2JsonConstant.DB2_USERS}_{self.pid}')
        return auth_key

    @property
    def server_type(self):
        server_type = self._get_param_field(ParamField.TYPE, self.application)
        return server_type if server_type else DB2Type.TYPE

    @property
    def sub_type(self):
        sub_type = self._get_param_field(ParamField.SUB_TYPE, self.application)
        return sub_type if sub_type else ""

    @staticmethod
    def get_body_error_param(code: int, body_error: int, message: str):
        params = {
            "code": code,
            "bodyErr": body_error,
            "message": message
        }
        return params

    def _get_param_field(self, field, param_dict=None):
        if param_dict is None:
            param_dict = self.param_dict
        target_value = None
        if not isinstance(param_dict, dict):
            return target_value
        target_value = param_dict.get(field)
        return target_value

    def _get_all_envinfo(self):
        if not SysData.SYS_STDIN:
            return False
        try:
            value_dict = json.loads(SysData.SYS_STDIN)
        except Exception as ex:
            return False
        auth_key = f'{Db2JsonConstant.DB2_USER}_{self.pid}'
        auth_pwd = f'{Db2JsonConstant.DB2_PWD}_{self.pid}'
        self._username = value_dict.get(auth_key)
        self._password = value_dict.get(auth_pwd)
        return True
